package com.starbaba.core.mybatis;

import com.base.common.database.DBPoolManager;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.Ordered;

import javax.sql.DataSource;
import java.util.Map;

/**
 * @author Yukinomiu
 * @version 1.0
 */
public class MybatisSpringPostProcessor implements BeanFactoryPostProcessor, Ordered {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        DBPoolManager dbPoolManager = DBPoolManager.getInstance();

        // get data source and register into spring container
        try {
            Class<DBPoolManager> clazz = DBPoolManager.class;
            java.lang.reflect.Field field = clazz.getDeclaredField("poollist");
            field.setAccessible(true);
            @SuppressWarnings("unchecked")
            Map<String, DataSource> dataSourceMap = (Map<String, DataSource>) field.get(dbPoolManager);

            for (String name : dataSourceMap.keySet()) {
                DataSource dataSource = dataSourceMap.get(name);
                if (dataSource != null) {
                    // register
                    configurableListableBeanFactory.registerSingleton(name, dataSource);
                }
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            // error log
            e.printStackTrace();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
